<template>
  <div class="post-item">
    <h3>{{ post.title }}</h3>
    <p class="post-meta">
      作者: <strong>{{ username }}</strong> | 发布时间:
      {{ formatDate(post.createTime) }}
    </p>

    <div class="post-content" v-html="sanitizedContent"></div>

    <div class="post-actions">
      <LikeButton
          :likes="post.likes"
          :is-liked="post.liked === true"
          @toggle-like="$emit('toggleLike')"
      />
      <button @click="toggleComments" class="comment-toggle-button">
        <span v-if="isLoadingComments">正在加载...</span>
        <span v-else>{{ showComments ? '收起评论' : `查看评论 (${post.commentCount})` }}</span>
      </button>
    </div>

    <CommentSection
        v-if="showComments"
        :comments="comments"
        @add-comment="handleAddNewComment"
    />
  </div>
</template>

<script setup>
import {ref, defineProps, defineEmits, computed, watchEffect} from 'vue';
import DOMPurify from 'dompurify';
import LikeButton from '../Forum/LikeButton.vue';
import CommentSection from '../Comment/CommentSection.vue';
import {postService} from "@/services/PostService.js";
import {userManager} from "@/utils/user.js";
import {userServie} from "@/services/user_service.js";

const props = defineProps({
  post: {
    type: Object,
    required: true,
  },
});

defineEmits(['toggleLike']);

const showComments = ref(false);
const isLoadingComments = ref(false);
const comments = ref([]);

const username = ref('');

watchEffect(async () => {
  if (props.post && props.post.author) {
    try {
      const user = await userServie.getUserById(props.post.author);
      username.value = user.username || '未知作者';
    } catch (error) {
      console.error("获取作者用户名失败:", error);
      username.value = '未知作者';
    }
  }
});

const sanitizedContent = computed(() => {
  return props.post.content ? DOMPurify.sanitize(props.post.content) : '';
});

const fetchCommentsForThisPost = async () => {
  isLoadingComments.value = true;
  try {
    const fetchedComments = await postService.getCommentsByPostId(props.post.id);
    comments.value = fetchedComments;
  } catch (error) {
    console.error(`获取帖子 ${props.post.id} 的评论失败:`, error);
  } finally {
    isLoadingComments.value = false;
  }
};

const toggleComments = async () => {
  showComments.value = !showComments.value;
  if (showComments.value) {
    await fetchCommentsForThisPost();
  }
};

const handleAddNewComment = async (commentContent) => {
  try {
    const commentData = {
      contenter:userManager.getUserId(),
      postId: props.post.id,
      content: commentContent,
    };
    await postService.createComment(commentData);

    alert("评论发表成功！");

    if (props.post.commentCount !== undefined) {
      props.post.commentCount++;
    }

    await fetchCommentsForThisPost();


  } catch (error) {
    console.error('发表评论失败:', error);
    alert('评论失败，请重试。');
  }
};

const formatDate = (dateValue) => {
  if (!dateValue) return '日期未知';
  const date = new Date(dateValue);
  if (isNaN(date.getTime())) return '无效日期';
  return date.toLocaleDateString();
};
</script>

<style scoped>
.post-item {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.post-item h3 {
  color: #333;
  margin-top: 0;
  margin-bottom: 10px;
}

.post-meta {
  font-size: 0.9em;
  color: #888;
  margin-bottom: 15px;
}

.post-content {
  color: #444;
  line-height: 1.6;
  margin-bottom: 20px;
  white-space: pre-wrap; /* Preserve whitespace and line breaks */
}

.post-actions {
  display: flex;
  gap: 15px;
  align-items: center;
  margin-top: 15px;
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.comment-toggle-button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.comment-toggle-button:hover {
  background-color: #0056b3;
}
</style>